var leftTreeConstructor = function(){
	
	var _this = this;
	this.treeView;
	
	function _init(n){
		
		var newtree = $('<div>');
		newtree.attr('id', "new-tree-" + n);
		newtree.addClass("new-tree");
		$("#treeview-left").append(newtree)
		
		_this.treeView = newtree.kendoTreeView({
            dragAndDrop: true,
            dataSource: []
        }).data("kendoTreeView");
	
		_OnSelectNode();
	}
	
	function _addElement(p_imageObj, p_settings){	

		//settings no acepta campo url
		var settings = {
				
			  angle: ""
			, height: ""
			, left: ""
			, scaleX: ""
			, scaleY: ""
			, source: ""
			, text: ""
			, top: ""
			, width: ""
			, zindex: ""
			, draggable: true
			, touchable: true
			, group: ""
			, initState: "Default"
			, opacity: 1
			, batchNode : null
		};
		
		$.extend(settings, p_settings);
		
		settings.zindex = _getZIndex(settings.zindex);
		
		if(_this.treeView.dataSource._data.length <= 0){
			_this.treeView.dataSource.add(settings);
			_this.treeView.dataSource._data[0].imageObj = p_imageObj
			_this.treeView.dataSource._data[0].imageObj.set('zindex', settings.zindex);
			_this.treeView.dataSource._data[0].imageObj.node = _this.treeView.findByUid(_this.treeView.dataSource._data[0].uid);
			
		}else{
			var lastElement = _this.treeView.dataSource._data[_this.treeView.dataSource._data.length-1];
			var node = _this.treeView.findByUid(lastElement.uid);			
			var nodeaux = _this.treeView.insertAfter(settings, node);	
			_this.treeView.dataSource._data[_this.treeView.dataSource._data.length-1].imageObj = p_imageObj;
			_this.treeView.dataSource._data[_this.treeView.dataSource._data.length-1].imageObj.node = nodeaux;
			_this.treeView.dataSource._data[_this.treeView.dataSource._data.length-1].imageObj.set('zindex', settings.zindex);
			
		}	
		
		mainCanvas.canvas._objects.sort(function(a,b){return a.zindex-b.zindex;});
		mainCanvas.canvas.renderAll();
		
	}
	
	function _OnSelectNode(){
		var node;
		
		_this.treeView.bind("select", function(e) {
			mainCanvas.canvas.discardActiveGroup()
			
			if(mainCanvas.canvas.getActiveObject()){
				mainCanvas.canvas.getActiveObject().setActive(false);
				mainCanvas.canvas.renderAll();
			}
			
			node = _this.treeView.dataSource.getByUid(e.node.dataset.uid);
			//window.console.log(_recursiveSelectNode(node));
			if(node.children._data.length == 0){
				
				mainCanvas.canvas.setActiveObject(node.imageObj);
				sliderController.updateControls();
			}
			else {
				
				var aux = new fabric.Group(_recursiveSelectNode(node));
				mainCanvas.canvas.setActiveGroup(aux);
				mainCanvas.canvas.renderAll();
				sliderController.updateControls();
			}
		});
		
	}
	
	
	function _recursiveSelectNode(p_node){
		
		var   auxArray = [];

		
		if(p_node.children._data.length==0){
			return [p_node.imageObj];
			
		}else{
			
			auxArray = [p_node.imageObj];
			
			for(var i = 0; i<p_node.children._data.length; i++){
				auxArray = auxArray.concat(_recursiveSelectNode(p_node.children._data[i]));
				
			}
		}	
		
		return auxArray;
	}
	
	function _unselectAllNodes(){
		var selected = leftTree.treeView.select();
		if (selected){
			selected.find("span.k-state-selected").removeClass("k-state-selected")
		}
		batchNodeController.select(false);
	}
	
	function _selected(){
		return leftTree.treeView.dataSource.getByUid(leftTree.treeView.select().attr('data-uid'));
	}
	
	function _getObjects(){
		
		var r = [];
		
		function add(data){
			
			$.each(data, function(i,e){
				
				var object = {
					id: e.uid,
					name: e.text
				}
				
				r.push(object);
				
				if (e.hasChildren){
					add(e.children.data())
				}
			})
		}
		
		add(leftTree.treeView.dataSource.data())
		
		return r;
	}
	
	
	//Si se indica un zindex ese será el fijado.
	//Si no, se calcula el máximo zindex de los elementos de la escena
	function _getZIndex(p_zindex){
		
		if (p_zindex){
			return p_zindex
		}
		
		var zindex = 0;
		
		$.each(leftTree.treeView.dataSource.data(), function(i,e){
			
			if (e.imageObj.hasOwnProperty('zindex') && e.imageObj.get('zindex') >= zindex){
				zindex = parseInt(e.imageObj.get('zindex')) + 1;
			}
		})
		
		return zindex
	}
	
	function _getAction(actionID){
		
		var action = false;
		var seqlength = leftTree.selected().sequences.length;
		var i = 0;
		
		while (!action && i < seqlength){
			
			var actLength = leftTree.selected().sequences[i].actions.length;
			var j = 0;
			
			while (!action && j < actLength){
				
				if (leftTree.selected().sequences[i].actions[j].idAction == actionID){
					
					action = leftTree.selected().sequences[i].actions[j].action
				}
				++j;
			}
			
			++i;
		}
		
		return action;
	}
	
	//devuelve la primera acción de nombre action del objeto obj
	function _getActionByName(p_obj,p_action){
		
		var obj = null
		  ,	l = leftTree.treeView.dataSource.data().length
		  , i = 0
		;
		
		while (!obj && i < l){
			if ( leftTree.treeView.dataSource.data()[i].text == p_obj ){
				obj = leftTree.treeView.dataSource.data()[i]
			}
			i++;
		}
		if (obj){
			
			var action = false;
			var seqlength = obj.sequences.length;
			var i = 0;
			
			while (!action && i < seqlength){
				
				var actLength = obj.sequences[i].actions.length;
				var j = 0;
				
				while (!action && j < actLength){
					
					if (obj.sequences[i].actions[j].action.name == p_action){
						action = obj.sequences[i].actions[j].action
						
						return {
								obj: obj, 
								seq: obj.sequences[i].actions, 
								index: j,
								duration: action.duration
							   }
					}
					++j;
				}
				
				++i;
			}
		}
	}
	
	function _removeAction(actionID){
		
		var action = false;
		var seqlength = leftTree.selected().sequences.length;
		var i = 0;
		
		while (!action && i < seqlength){
			
			var actLength = leftTree.selected().sequences[i].actions.length;
			var j = 0;
			
			while (!action && j < actLength){
				
				if (leftTree.selected().sequences[i].actions[j].idAction == actionID){
					
					leftTree.selected().sequences[i].actions.splice(j,1);
					action = true;
				}
				++j;
			}
			
			++i;
		}
		
		return action;
	}
	
	this.init = _init;
	this.addElement = _addElement;
	this.unselectAllNodes = _unselectAllNodes;
	this.selected = _selected
	this.getObjects = _getObjects;
	this.getAction = _getAction;
	this.removeAction = _removeAction;
	this.getActionByName = _getActionByName;
	
	return this;
	
}


